﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using XKPlatform.Common.Enums;
using XKPlatform.DataModels.ReturnModel;

namespace XKPlatform.Controllers.SysController
{
    [Route("[controller]/[action]")]
    public class CommonUtilController : BaseController
    {
        //excel 数据导入通用功能
        private readonly IImportTableDataService _importTableDataService;
        public CommonUtilController(IImportTableDataService importTableDataService,IHttpContextAccessor httpContext) : base(httpContext)
        {
            _importTableDataService = importTableDataService;
        }
        /// <summary>
        /// 导入表数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [RequestFormLimits(MultipartBodyLengthLimit = 209715200)]
        [RequestSizeLimit(209715200)]
        public JsonResult Import()
        {
            var file = Request.Form.Files[0];

            if (file == null)
            {
                return Json(new BaseModel { code = (int)MsgCodeEnum.InvalidParameter, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.InvalidParameter) });
            }

            IList<string> list = new List<string>() { ".xlsx", ".xls" };
            if (!list.Contains(Path.GetExtension(file.FileName)))
            {
                return Json(new BaseModel { code = (int)MsgCodeEnum.InvalidParameter, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.InvalidParameter) });
            }

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            (int, IList<string>) items = _importTableDataService.ImportData(file, Request.Form["TempNum"].ToString());

            stopwatch.Stop();


            return Json(new { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success), data = items.Item1, messages = items.Item2, time = stopwatch.ElapsedMilliseconds });

        }
    }
}
